import { stringify } from 'qs';
import _ from 'lodash';
import request from '../utils/request';
import { ipConfig } from './config';

const PATH = '/api-ms/system/users';

export const userInfo = async () => request(`${ipConfig.url(PATH)}/info`, { method: 'GET' }).then(mapUserInfo);

const mapUserInfo = rsp => {
  const response = rsp.data;
  const user = {
    id: response.userId,
    name: response.userName,
    staff: {
      id: response.staffId,
      name: response.staffName,
    },
    organization: {
      id: response.orgId,
      code: response.orgCode,
      name: response.orgName,
      type: response.orgType,
    },
    corporation: {
      id: response.corpId,
      code: response.corpCode,
      name: response.corpName,
      type: response.corpType,
    },
  };
  return user;
};

export const staffInfo = async userID => {
  const params = { userId: userID, status: 0 };
  return request(`${ipConfig.url(PATH)}/staffinfo?${stringify(params)}`, {
    method: 'GET',
  }).then(mapStaffInfo);
};

const mapStaffInfo = rsp => {
  const response = rsp.data;
  const staff = {
    id: response.staffId,
    name: response.staffName,
    _no: response.staffNo,
    duty: response.duty,
    posts: response.sysPosts,
    prfile: {
      tel: response.telNo,
      sex: response.sex,
      email: response.email,
    },
  };
  return staff;
};

export const infoOfUserAndStaff = async () => {
  const user = await userInfo();
  const staff = await staffInfo(user.id);
  return { ...user, staff };
};


// http://mesdev.chalco-steering.com:1708/appgateway/api-ms/externalSys/sysAppUser/resources
const appUserPATH = '/api-ms/externalSys/sysAppUser';

export const resources = async () => request(`${ipConfig.url(appUserPATH)}/resources`, {
  method: 'GET',
}).then(mapAuthorities);

const mapAuthorities = rsp => _.keys(rsp.data);

export const infoOfUserAndStaffCarryResources = async () => Promise
  .all([infoOfUserAndStaff(), resources()])
  .then(values => ({ ...values[0], authorities: values[1] }));
